/**
 * 
 */
package com.ls.lsqc.modules.sys.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Maps;
import com.ls.lsqc.common.config.Global;
import com.ls.lsqc.common.security.shiro.session.SessionDAO;
import com.ls.lsqc.common.servlet.ValidateCodeServlet;
import com.ls.lsqc.common.utils.CacheUtils;
import com.ls.lsqc.common.utils.Constants;
import com.ls.lsqc.common.utils.CookieUtils;
import com.ls.lsqc.common.utils.IdGen;
import com.ls.lsqc.common.utils.SendMailUtil;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.utils.UserAgentUtils;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.order.entity.StyleOptionEntity;
import com.ls.lsqc.modules.produce.service.CustomizationQualityService;
import com.ls.lsqc.modules.sys.entity.OrderQualityCount;
import com.ls.lsqc.modules.sys.entity.QualityCount;
import com.ls.lsqc.modules.sys.entity.User;
import com.ls.lsqc.modules.sys.security.FormAuthenticationFilter;
import com.ls.lsqc.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.ls.lsqc.modules.sys.service.SystemService;
import com.ls.lsqc.modules.sys.utils.UserUtils;

/**
 * 登录Controller
 * 
 * @author
 * @version 2013-5-31
 */
@Controller
public class LoginController extends BaseController {

	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private LocaleResolver localeResolver;
	@Autowired
	private SystemService systemService;
	@Autowired
	private CustomizationQualityService customizationQualityService;

	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();
		String url = "";
		if (UserAgentUtils.isMobileOrTablet(request)) {
			url = "sys/sysMobileLogin";
		} else {
			url = "modules/sys/sysLogin";
		}
		// // 默认页签模式
		// String tabmode = CookieUtils.getCookie(request, "tabmode");
		// if (tabmode == null){
		// CookieUtils.setCookie(response, "tabmode", "1");
		// }

		if (logger.isDebugEnabled()) {
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			CookieUtils.setCookie(response, "LOGINED", "false");
		}

		// 如果已经登录，则跳转到管理首页
		if (principal != null && !principal.isMobileLogin()) {
			return "redirect:" + adminPath;
		}
		// String view;
		// view = "/WEB-INF/views/modules/sys/sysLogin.jsp";
		// view = "classpath:";
		// view +=
		// "jar:file:/D:/GitHub/jeesite/src/main/webapp/WEB-INF/lib/jeesite.jar!";
		// view += "/"+getClass().getName().replaceAll("\\.",
		// "/").replace(getClass().getSimpleName(), "")+"view/sysLogin";
		// view += ".jsp";
		return url;
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();

		// 如果已经登录，则跳转到管理首页
		if (principal != null) {
			return "redirect:" + adminPath;
		}

		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
			// 用户或密码错误, 请重试.
			message = getText("password_wrong_please_try");
		}

		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

		if (logger.isDebugEnabled()) {
			logger.debug("login fail, active session size: {}, message: {}, exception: {}",
					sessionDAO.getActiveSessions(false).size(), message, exception);
		}

		// 非授权异常，登录失败，验证码加1。
		if (!UnauthorizedException.class.getName().equals(exception)) {
			model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
		}

		// 验证失败清空验证码
		request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());

		// 如果是手机登录，则返回JSON字符串
		if (mobile) {
			return renderString(response, model);
		}

		return "modules/sys/sysLogin";
	}

	/**
	 * 登录成功，进入管理首页
	 * @throws Exception 
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

		Principal principal = UserUtils.getPrincipal();
		String url = "";
		request.getSession().setAttribute(Constants.LANGUAGE,
				localeResolver.resolveLocale(request).toString().toLowerCase());

		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(principal.getLoginName(), false, true);

		model.addAttribute("user", UserUtils.getUser());

		if (logger.isDebugEnabled()) {
			logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)) {
				CookieUtils.setCookie(response, "LOGINED", "true");
			} else if (StringUtils.equals(logined, "true")) {
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		}

		// 如果是手机登录,返回对应的地址。
		if (UserAgentUtils.isMobileOrTablet(request)) {
			url = "sys/erpMobileMenuIndex";
		} else {
			//当是质检组的员工进入系统时，直接跳转到质检画面
			int groupId = systemService.getGroupId(UserUtils.getUser().getId());
			if (groupId == 38) {
				url = "modules/produce/CustomizationQualityButtonEnter";
			} else {
				Date endDate = new Date();
				Calendar date = Calendar.getInstance();
				date.setTime(endDate);
				date.set(Calendar.DATE, date.get(Calendar.DATE) - 6);
				Date beginDate = date.getTime();
				
				Calendar dateTemp = Calendar.getInstance();
				dateTemp.setTime(endDate);
				dateTemp.set(Calendar.DATE, dateTemp.get(Calendar.DATE) - 6);
				Date beginDateTemp = dateTemp.getTime();
				//统计订单数量
				List<OrderQualityCount> orderQualityList = new ArrayList()/*systemService.getOrderQualityCount(new Date(),beginDate)*/;
				model.addAttribute("orderQualityList",orderQualityList);
				//统计质检数量
				List <QualityCount> qualityListALL = new ArrayList<>();/*systemService.getQualityCount(new Date(),beginDateTemp)*/;
				model.addAttribute("qualityList",qualityListALL);
				model.addAttribute("beginDate",beginDateTemp);
				model.addAttribute("endDate",new Date());
				url = "modules/sys/erpMenuIndex";
			}
		}

		// // 登录成功后，获取上次登录的当前站点ID
		// UserUtils.putCache("siteId",
		// StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));

		// System.out.println("==========================a");
		// try {
		// byte[] bytes = com.ssm.lsmtm.common.utils.FileUtils.readFileToByteArray(
		// com.ssm.lsmtm.common.utils.com.ls.lsqcile("c:\\sxt.dmp"));
		// UserUtils.getSession().setcom.ls.lsqc", bytes);
		// UserUtils.getSession().setAttribute("kkk2", bytes);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//// for (int i=0; i<1000000; i++){
		//// //UserUtils.getSession().setAttribute("a", "a");
		//// request.getSession().setAttribute("aaa", "aa");
		//// }
		// System.out.println("==========================b");
		return url;
	}
	@RequestMapping(value = "${adminPath}/customizationEnter")
	public String customizationEnter(String operatingId,HttpServletRequest request,Model model) throws Exception{
		model.addAttribute("operatingId",operatingId);
		model.addAttribute("user",UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
		return "modules/produce/CustomizationQualityEnter";
	}
	
	/**
	 * 获取订单相关数量
	 */
	@RequestMapping(value = "${adminPath}/getOrderQuantity")
	public String getQuantity(Date endDate, Date beginDate,Model model,HttpServletResponse response) {
		List<OrderQualityCount> orderQualityList = systemService.getOrderQualityCount(endDate,beginDate);
		model.addAttribute("orderQualityList",orderQualityList);
		return "modules/sys/erpMenuIndex";
	}

	/**
	 * 获取质检相关数量
	 */
	@RequestMapping(value = "${adminPath}/getQuantityInspection")
	public String getQuantityInspection(Date endDate, Date beginDate,Model model,HttpServletResponse response) {
		List <QualityCount> qualityListALL = systemService.getQualityCount(endDate,beginDate);
		model.addAttribute("qualityList",qualityListALL);
		return "modules/sys/erpMenuIndex";
	}
	

	

	
	



	

	private String getToString(List<OrderQualityCount> list,String toStr) {
		String strTemp = "";
		for (int i = 0; i < list.size();i++) {
			if  (i<list.size()) {
				if ("qualityDate".equals(toStr)) {
					strTemp +=list.get(i).getQualityDate()+",";
				} else if ("platformQuantity".equals(toStr)) {
					strTemp +=list.get(i).getPlatformQuantity()+",";
				} else if ("hollandQuantity".equals(toStr)) {
					strTemp +=list.get(i).getHollandQuantity()+",";
				} else if ("totalQuantity".equals(toStr)) {
					strTemp +=list.get(i).getTotalQuantity()+",";
				} else if ("completedQuantity".equals(toStr)) {
					strTemp +=list.get(i).getCompletedQuantity()+",";
				} else if ("notCompletedQuantity".equals(toStr)) {
					strTemp +=list.get(i).getNotCompletedQuantity()+",";
				}
			} else if (i== (list.size()-1)){
				if ("qualityDate".equals(toStr)) {
					strTemp +=list.get(i).getQualityDate();
				} else if ("platformQuantity".equals(toStr)) {
					strTemp +=list.get(i).getPlatformQuantity();
				} else if ("hollandQuantity".equals(toStr)) {
					strTemp +=list.get(i).getHollandQuantity();
				} else if ("totalQuantity".equals(toStr)) {
					strTemp +=list.get(i).getTotalQuantity();
				} else if ("completedQuantity".equals(toStr)) {
					strTemp +=list.get(i).getCompletedQuantity();
				} else if ("notCompletedQuantity".equals(toStr)) {
					strTemp +=list.get(i).getNotCompletedQuantity();
				}
			}
		} 
		
		return strTemp;
	}
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isNotBlank(theme)) {
			CookieUtils.setCookie(response, "theme", theme);
		} else {
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:" + request.getParameter("url");
	}

	/**
	 * 是否是验证码登录
	 * 
	 * @param useruame
	 *          用户名
	 * @param isFail
	 *          计数加1
	 * @param clean
	 *          计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean) {
		Map<String, Integer> loginFailMap = (Map<String, Integer>) CacheUtils.get("loginFailMap");
		if (loginFailMap == null) {
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum == null) {
			loginFailNum = 0;
		}
		if (isFail) {
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean) {
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}

	/**
	 * @Title: sysLoginForgetPassword @Description: 忘记密码 @param @return @return
	 * String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/sysLoginForgetPassword")
	public String sysLoginForgetPassword(Model model) {
		User user = new User();
		model.addAttribute("user", user);
		return "modules/sys/sysLoginForgetPassword03";
	}

	/**
	 * @Title: checkEmail @Description: 邮箱验证 @param @param user @param @param
	 * redirectAttributes @param @param model @param @return @return
	 * String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/checkEmail")
	@ResponseBody
	public String checkEmail(String email) {
		try {
			User user = new User();
			user.setEmail(email);
			if (email != null && systemService.checkEmailName(user) != null) {
				// 返回true
				return "true";
			}
			// 数据值重名
			return "false";

		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}
		// 数据值重名
		return "false";
	}

	/**
	 * @Title: sysLoginForgetPassword02 @Description: 确认邮件 @param @param
	 * user @param @param request @param @param redirectAttributes @param @param
	 * model @param @param response @param @return @return String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/sysLoginForgetPassword02")
	public String sysLoginForgetPassword02(User user, HttpServletRequest request, RedirectAttributes redirectAttributes,
			Model model, HttpServletResponse response) {
		// 发送email
		sendForgetPassword(user, request);
		return "modules/sys/sysLoginForgetPassword02";
	}

	/**
	 * @Title: forgetPasswordResend @Description: 发送邮件 @param @param
	 * user @param @param request @param @param redirectAttributes @param @param
	 * model @param @return @return String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/forgetPasswordResend")
	public String forgetPasswordResend(User user, HttpServletRequest request, RedirectAttributes redirectAttributes,
			Model model) {
		// 发送email
		sendForgetPassword(user, request);
		return null;
	}

	/**
	 * @Title: sendForgetPassword @Description: 发送邮件 @param @param
	 * user @param @param request @return void @throws
	 */

	private void sendForgetPassword(User user, HttpServletRequest request) {
		User updateEmail = new User();
		updateEmail.setId(systemService.checkEmailName(user).getId());
		updateEmail.setEmailRandomCode(IdGen.uuid());
		updateEmail.setEmailSendTime(new Date());
		systemService.updateCheckEmailById(updateEmail);
		// 发送email
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + Global.getAdminPath() + "/forgetPassword/sysLoginForgetPassword03?loginName="
				+ systemService.checkEmailName(user).getLoginName() + "&emailRandomCode=" + updateEmail.getEmailRandomCode();
		SendMailUtil.sendCommonMail(user.getEmail(), getText("modifyPassword"), "<a href='" + url + "'>" + url + "</a>");
	}

	/**
	 * @Title: sysLoginForgetPassword03 @Description: 修改密码 @param @param
	 * user @param @param redirectAttributes @param @param
	 * model @param @return @return String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/sysLoginForgetPassword03")
	public String sysLoginForgetPassword03(User user, RedirectAttributes redirectAttributes, Model model) {
		// 从邮箱跳转到该页面
		User newPassword = systemService.getByLoginName(user.getLoginName());

		if (newPassword.getEmailRandomCode().equals(user.getEmailRandomCode())
				&& failureTime(newPassword.getEmailSendTime())) {
			// 验证码通过验证
			User updateEmail = new User();
			updateEmail.setId(newPassword.getId());
			updateEmail.setEmailRandomCode(null);
			updateEmail.setEmailSendTime(null);
			systemService.updateCheckEmailById(updateEmail);
		} else {
			User updateEmail = new User();
			updateEmail.setId(newPassword.getId());
			updateEmail.setEmailRandomCode(null);
			updateEmail.setEmailSendTime(null);
			systemService.updateCheckEmailById(updateEmail);
			return "redirect:" + adminPath;
		}
		model.addAttribute("user", newPassword);
		return "modules/sys/sysLoginForgetPassword03";
	}

	/**
	 * @Title: failureTime @Description: 验证失效时间24小时之内 @param @param
	 * date @param @return @return Boolean @throws
	 */

	public Boolean failureTime(Date date) {

		long cha = new Date().getTime() - date.getTime();
		// 换算时间
		double result = cha * 1.0 / (1000 * 60 * 60);
		// 是否超过24小时
		if (result <= 24) {
			// 未失效
			return true;

		} else {
			// 失效
			return false;
		}
	}

	/**
	 * @Title: sysLoginForgetPassword04 @Description: 保存密码 @param @param
	 * user @param @param oldPassword @param @param
	 * redirectAttributes @param @param model @param @param
	 * response @param @return @return String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/sysLoginForgetPassword04")
	public String sysLoginForgetPassword04(User user, String oldPassword, RedirectAttributes redirectAttributes,
			Model model, HttpServletResponse response) {
		User newPassword = systemService.getByLoginName(user.getLoginName());
		newPassword.setPassword(SystemService.entryptPassword(user.getPassword()));
		// 保存密码
		systemService.updatePassword(newPassword);
		model.addAttribute("user", user);
		// 提示保存成功信息
		return "modules/sys/sysLoginForgetPassword04";
	}
	
	/**
	 * @Title: sysCheckLoginNameExist @Description: 用户名查存 @param @param
	 * user @param @param
	 * redirectAttributes @param @param model @param @param
	 * response @param @return @return String @throws
	 */

	@RequestMapping(value = "${adminPath}/forgetPassword/sysCheckLoginNameExist")
	public String sysCheckLoginNameExist(User user, String oldPassword, RedirectAttributes redirectAttributes,
			Model model, HttpServletResponse response) {
		User newPassword = systemService.getByLoginName(user.getLoginName());
		String flag = "false";
		if (newPassword != null) {
			flag = "true";
		}
		return renderString(response, flag);
	}
}
